// pages/i_trade/i_trade.js
var util = require('../../utils/util.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
// 实例化腾讯地图API核心类
var demo = new QQMapWX({
  key: 'ZOKBZ-3YZK3-IBW34-YKATO-EPPYO-D7BR2' // 必填 。
});
const app = getApp()
var add_order;var save_order_img;var flag = 1;

function uploadimg(data) {
  console.log(data);
  var that = this,
    i = data.i ? data.i : 0,
    success = data.success ? data.success : 0,
    fail = data.fail ? data.fail : 0;
  wx.uploadFile({
    url: data.url,
    filePath: data.path[i],
    name: 'file',
    formData: {
      id: data.id,
      type: data.type
    },
    success: function (res) {
      success++;
      console.log(res)
      console.log(i);
      console.log(data.id);
    },
    fail: function (res) {
      fail++;
      console.log('fail:' + i + "fail:" + fail);
    },
    complete: function (res) {
      console.log(i);
      i++;
      if (i == data.path.length) {   //当图片传完时，停止调用   
        console.log('执行完毕');
        console.log('成功：' + success + " 失败：" + fail);
      } else {
        console.log(i);
        data.i = i;
        data.success = success;
        data.fail = fail;
        uploadimg(data);
      }

    }
  });
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['狗', '猫', '其他'],
    index:0,
    array1: ['请选择', '宠物专车', '空运', '铁路托运', '大巴托运'],
    index1:0,
    array2: [ '幼年', '成年'],
    index2:0,
    array3: ['1', '2', '3', '4', '5'],
    index3:0,
    time:'请选择',//期望时间
    service:[
      {name:'上门接宠',select:false},
      {name:'送宠到家',select:false},
      {name:'需宠具',select:false}
    ],
    ser_index:-1,
    ftime:[],
    ftime_index:0,
    xz_time:'',
    fdate:[
      {name:'上午',select:true},
      {name:'下午',select:false}
    ],
    xz_date:'上午',
    fix:false,
    tempFilePaths:[],
    f_id:'',
    f_name:'',
    f_mobile:'',
    f_area:'',
    f_city:'',
    f_addr:'',
    f_lat:'',
    f_lng:'',
    s_id:'',
    s_name:'',
    s_mobile:'',
    s_area:'',
    s_city:'',
    s_addr:'',
    s_lat:'',
    s_lng:'',
    name:'',
    remark:'',
    weight:'',
    select:false,
    smjc:'',
    scdj:'',
    lj:'',
  },
  xztap:function(e){
    this.setData({
      select:!this.data.select
    })
  },
  nametap:function(e){
    this.setData({
      name:e.detail.value
    })
  },
  remarktap:function(e){
    this.setData({
      remark:e.detail.value
    })
  },
  weighttap:function(e){
    this.setData({
      weight:e.detail.value
    })
  },
  hidetap:function(e){
    this.setData({
      fix:false
    })
  },
  showtap:function(e){
    this.setData({
      fix:true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var now_date =  util.formatDate(new Date());
    var getDates = util.getDates(60, now_date);
    var date = [];
    for(var i=0;i<getDates.length;i++){
      var time = getDates[i].year+'-'+getDates[i].month+'-'+getDates[i].day;
      date.push(time);
    }
    that.setData({
      ftime: date,
      xz_time:date[0]
    })
    add_order = app.data.index_url + 'add_order';
    save_order_img = app.data.index_url + 'save_order_img';
    
  },
  getDistance: function (la1, lo1, la2, lo2, that, i) {
    var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137;
    s = (Math.round(s * 10000) / 10000).toFixed(2);
    return s;
  },
  xytap:function(e){
    wx.navigateTo({
      url: '/pages/i_xy/i_xy?name=ykxy',
    })
  },
  imgdeltap:function(e){
    var that = this;
    var tempFilePaths = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index;
    tempFilePaths.splice(index,1);
    that.setData({
      tempFilePaths:tempFilePaths
    })
  },
  chooseimage: function (e) {
    var that = this;
    var tempFilePaths = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index;
    var img = tempFilePaths;
    wx.chooseImage({
      count: 6, // 默认9  
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        for (var i = 0; i < imgsrc.length; i++) {
          img.push(imgsrc[i])
        }
        console.log(img);
        that.setData({
          tempFilePaths: img
        })
      }
    })
  },
  Faddrxqtap:function(e){
    var f_id = this.data.f_id;
    if(f_id == ''){
      wx.navigateTo({
        url: '/pages/i_addressxq/i_addressxq?type=0',
      })
    }else{
      wx.navigateTo({
        url: '/pages/i_addressxq/i_addressxq?type=0&id='+f_id,
      })
    }
  },
  Faddrtap:function(e){
    wx.navigateTo({
      url: '/pages/i_addrF/i_addrF?type=0',
    })
  },
  Saddrxqtap:function(e){
    var s_id = this.data.s_id;
    if(s_id == ''){
      wx.navigateTo({
        url: '/pages/i_addressxq/i_addressxq?type=1',
      })
    }else{
      wx.navigateTo({
        url: '/pages/i_addressxq/i_addressxq?type=1&id='+s_id,
      })
    }
  },
  Saddrtap:function(e){
    wx.navigateTo({
      url: '/pages/i_addrS/i_addrS?type=1',
    })
  },
  sertap:function(e){
    var that = this;
    var service = that.data.service;
    var index = e.currentTarget.dataset.index;
    if(index == 0 && service[index].select == false){
      that.setData({
        smjc:service[index].name
      })
    }
    if(index == 0 && service[index].select == true){
      that.setData({
        smjc:''
      })
    }
    if(index == 1 && service[index].select == false){
      that.setData({
        scdj:service[index].name
      })
    }
    if(index == 1 && service[index].select == true){
      that.setData({
        scdj:''
      })
    }
    if(index == 2 && service[index].select == false){
      that.setData({
        lj:service[index].name
      })
    }
    if(index == 2 && service[index].select == true){
      that.setData({
        lj:''
      })
    }
    service[index].select = !service[index].select;
    that.setData({
      service:service
    })
  },
  fixtimetap:function(e){
    var that = this;
    var ftime = that.data.ftime;
    var index = e.currentTarget.dataset.index;
    var xz_time = ftime[index];
    that.setData({
      ftime_index:index,
      xz_time:xz_time
    })
  },
  fixdatetap:function(e){
    var that = this;
    var fdate = that.data.fdate;
    var index = e.currentTarget.dataset.index;
    for(var i=0;i<fdate.length;i++){
      if(index == i){
        fdate[i].select = true;
      }else{
        fdate[i].select = false;
      }
    }
    that.setData({
      fdate:fdate,
      xz_date:fdate[index].name
    })
  },
  fixtap:function(e){
    var that = this;
    var xz_time = that.data.xz_time;
    var xz_date = that.data.xz_date;
    var time = xz_time+' '+xz_date;
    that.setData({
      time:time,
      fix:false
    })
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  bindPickerChange1: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index1: e.detail.value
    })
  },
  bindPickerChange2: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index2: e.detail.value
    })
  },
  bindPickerChange3: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index3: e.detail.value
    })
  },
  submit:function(e){
    var that = this;
    if(flag == 1){
      flag = 0;
      var array1 = that.data.array1;
      var index1 = that.data.index1;
      if(index1 == 0){
        wx.showModal({
          title: '提示',
          content: '请选择托运方式',
          showCancel: false
        })
        flag = 1;
        return false;
      }
      var ps_way = array1[index1];
      var f_name = that.data.f_name;
      var f_mobile = that.data.f_mobile;
      var f_area = that.data.f_area;
      var f_city = that.data.f_city;
      var f_addr = that.data.f_addr;
      if(f_name == ''){
        wx.showModal({
          title: '提示',
          content: '请填写发宠人信息',
          showCancel: false
        })
        flag = 1;
        return false;
      }
      var s_name = that.data.s_name;
      var s_mobile = that.data.s_mobile;
      var s_area = that.data.s_area;
      var s_city = that.data.s_city;
      var s_addr = that.data.s_addr;
      if(s_name == ''){
        wx.showModal({
          title: '提示',
          content: '请填写收宠人信息',
          showCancel: false
        })
        flag = 1;
        return false;
      }
      var array = that.data.array;
      var index = that.data.index;
      var pets_type = array[index];
      var array3 = that.data.array3;
      var index3 = that.data.index3;
      var num = array3[index3];
      var array2 = that.data.array2;
      var index2 = that.data.index2;
      var age = array2[index2];
      var name = that.data.name;
      var stime = that.data.time;
      if(stime == '请选择'){
        wx.showModal({
          title: '提示',
          content: '请选择期望出发时间',
          showCancel: false
        })
        flag = 1;
        return false;
      }
      var weight = that.data.weight;
      if(weight == ''){
        wx.showModal({
          title: '提示',
          content: '请填写宠物重量',
          showCancel: false
        })
        flag = 1;
        return false;
      }
      var smjc = that.data.smjc;
      var scdj = that.data.scdj;
      var lj = that.data.lj;
      // if(smjc == '' && scdj == '' && lj == ''){
      //   wx.showModal({
      //     title: '提示',
      //     content: '请选择接送服务',
      //     showCancel: false
      //   })
      //   flag = 1;
      //   return false;
      // }
      var remark = that.data.remark;
      var tempFilePaths = that.data.tempFilePaths;
      if(tempFilePaths.length == 0){
        wx.showModal({
          title: '提示',
          content: '请上传宠物图片',
          showCancel: false
        })
        flag = 1;
        return false;
      }
      var select = that.data.select;
      if(select == false){
        wx.showModal({
          title: '提示',
          content: '请阅读并同意《服务条款》',
          showCancel: false
        })
        flag = 1;
        return false;
      }
      var jl = that.getDistance(that.data.f_lat, that.data.f_lng, that.data.s_lat, that.data.s_lng);
      var aid = wx.getStorageSync('uid');
      wx.showLoading();
      wx.request({
        url: add_order,
        data: {
          uid:aid,
          ps_way:ps_way,
          f_name:f_name,
          f_mobile:f_mobile,
          f_area:f_area,
          f_city:f_city,
          f_addr:f_addr,
          s_name:s_name,
          s_mobile:s_mobile,
          s_area:s_area,
          s_city:s_city,
          s_addr:s_addr,
          pets_type:pets_type,
          num:num,
          age:age,
          name:name,
          stime:stime,
          weight:weight,
          smjc:smjc,
          scdj:scdj,
          lj:lj,
          remark:remark,
          distance:jl
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res.data);
          if(res.data.state == 1){
            var id = res.data.id;
            console.log(id);
            uploadimg({
              url: save_order_img,//这里是你图片上传的接口
              path: tempFilePaths,//这里是选取的图片的地址数组
              id: id
            });
            setTimeout(function(e){
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '订单发布成功！',
                showCancel: false,
                success: function (e) {
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                }
              })
            },500)
          }
        }
      })
    }
  },  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    flag = 1;
    var f_id = app.data.f_id;
    var f_name = app.data.fname;
    var f_mobile = app.data.fmobile;
    var f_area = app.data.farea;
    var f_city = app.data.fcity;
    var f_addr = app.data.faddr;
    var s_id = app.data.s_id;
    var s_name = app.data.sname;
    var s_mobile = app.data.smobile;
    var s_area = app.data.sarea;
    var s_city = app.data.scity;
    var s_addr = app.data.saddr;
    if(f_addr != ''){
      var f_address = f_area+f_addr;
      demo.geocoder({
        address: f_address, //地址参数
        success: function (res) {
          console.log(res);
          var res = res.result;
          var lat = res.location.lat;
          var lng = res.location.lng;
          that.setData({
            f_lat:lat,
            f_lng:lng
          })
        }
      })
    }
    if(s_addr != ''){
      var s_address = s_area+s_addr;
      demo.geocoder({
        address: s_address, //地址参数
        success: function (res) {
          console.log(res);
          var res = res.result;
          var lat = res.location.lat;
          var lng = res.location.lng;
          that.setData({
            s_lat:lat,
            s_lng:lng
          })
        }
      })
    }
    setTimeout(function(e){
      var jl = that.getDistance(that.data.f_lat, that.data.f_lng, that.data.s_lat, that.data.s_lng);
      console.log(jl);
    },500)
    that.setData({
      f_id:f_id,
      f_name:f_name,
      f_mobile:f_mobile,
      f_area:f_area,
      f_city:f_city,
      f_addr:f_addr,
      s_id:s_id,
      s_name:s_name,
      s_mobile:s_mobile,
      s_area:s_area,
      s_city:s_city,
      s_addr:s_addr
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})